const express = require("express");
const mongoose = require("mongoose");
const authRouter = require("./routers/auth");
const bodyParser = require("body-parser");
const md5 = require("md5");
const orders = require("./routers/orders");
const address = require("./routers/address");
const partment = require("./routers/partment");
const user = require("./routers/user");
const addgoods = require("./routers/addgoods");
const wechat = require("./routers/wechat");
const addwarehouse = require("./routers/addwarehouse");
const wxorders = require("./routers/Wxorders");
// 连接数据库
mongoose
  .connect("mongodb://127.0.0.1:27017/index")
  .then(() => {
    console.log("数据库连接成功");
    // 启动服务器
    const app = express();
    app.use(
      bodyParser.json({
        limit: "100mb",
      })
    );
    app.use(
      bodyParser.urlencoded({
        limit: "100mb",
        extended: true,
      })
    );
    // 使用中间件处理参数
    app.use(express.json()); //json格式'{"a": 1, "b": 2}'
    app.use(express.urlencoded()); //url-encode a=1&b=2

    // 使用路由处理请求
    app.use("/api/auth", authRouter);
    app.use("/api/orders", orders);
    app.use("/api/address", address);
    app.use("/api/addwarehouse", addwarehouse);
    app.use("/api/partment", partment); //部门管理
    app.use("/api/user", user);
    // app.use("/api/partment", partment);
    app.use("/api/addgoods", addgoods);
    app.use("/api/wechat", wechat);
    app.use("/api/wxorders", wxorders);
    //配置静态资源文件
    app.listen(8000, "localhost", async () => {
      console.log("服务器启动成功....");
      const User = require("./model/User");
      let res = await User.find({ username: "admin" });
      // console.log(res);
      if (res.length == 0) {
        User.create({
          username: "admin",
          password: md5("admin"),
          telephone: 13467341601,
        });
        return;
      }
    });
  })
  .catch((error) => {
    console.log("数据库连接失败:", error);
  });
